package com.otod.commons.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import com.otod.base.exception.AppException;
import com.otod.sys.file.service.IFileService;


/**
 * 文件操作工具类。
 * @author jqiu
 */
public class FileUtil {
    //这个类不能实例化
    private FileUtil() {
    }

    /**
     * 删除文件
     * @param fullname 文件路径+文件名
     * @return	boolean 是否删除成功
     */
	public static boolean deleteFile(String fullname){
		File file = new File(fullname);
		return file.delete();
	}
	
	
	/**
	 * 保存文件到通用附件表
	 * @param attachIds 附件主建ID
	 * @param busiId	业务主键
	 * @throws AppException
	 */
//	public static void saveFileToComAttachTabel(String attachIds,String busiId) throws AppException{
//		if(!StringUtils.isEmpty(attachIds)){
//			IFileService bsifileInfoService = (IFileService)SpringContextHolder.getBean(IFileService.BEAN_ID);
//			bsifileInfoService.updateFileInfoBusiId(attachIds.split(","), busiId);  	/*更新附件信息buisId*/
//		}
//	}
	
	
	/**
	 * 通过业务ID从通用附件表中删除附件
	 * @param busiId	业务主键
	 * @throws AppException
	 */
	public static void deleteFileFromComAttachTabel(String busiId) throws AppException{
		if(!StringUtils.isEmpty(busiId)){
			IFileService bsifileInfoService = (IFileService)SpringContextHolder.getBean(IFileService.BEAN_ID);
			bsifileInfoService.deleteFileByBusiId(busiId);
		}
	}
	
	
	/**
	 * 文件拷贝
	 * @param srcFile		源文件
	 * @param destFilePath	目标位置
	 */
	public static void copyFile(File srcFile,String destFilePath){
		InputStream in=null;
		OutputStream out = null;
		try{
			in = new BufferedInputStream(new FileInputStream(srcFile));		
			out = new BufferedOutputStream(new FileOutputStream(destFilePath));				
			for (int b=in.read();b!=-1;b=in.read()){			
				out.write(b);
			}		
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(in != null){
					in.close();
				}
				if(out != null){
					out.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
}
